<?php


namespace App\Http\Controllers\Admin\Content;


use App\Http\Controllers\AdminController;
use App\Models\Content\Article;
use App\Models\Content\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ArticleController extends AdminController
{

    public function data(Request $request)
    {
        $model = Article::query()->select(['id', 'sort', 'category_id', 'title', 'thumb', 'status', 'created_at', 'updated_at']);
        if ($groupId = $request->get('groupId')) {
            $model->where('category_id', (int)$groupId);
        }
        if ($keywords = $request->get('keywords')) {
            $model->where('title', 'like', filterStr($keywords).'%');
        }
        $list = $model->orderBy('sort')->paginate($request->get('limit', 10));
        return $this->succeed([
            'total' => $list->total(),
            'rows'  => $list->items(),
        ]);
    }

    public function getAllCategory()
    {
        return $this->succeed(Category::query()->select(['id', 'name'])->orderBy('sort')->get());
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|unique:articles|max:120',
            'url' => 'nullable|active_url',
        ]);
        $data = $request->only(['sort', 'category_id', 'title', 'desc', 'thumb', 'content', 'url', 'status']);
        try {
            DB::transaction(function () use ($data) {
                $model = Article::query()->create([
                    'sort' => (int)$data["sort"],
                    'category_id' => (int)$data['category_id'],
                    'title' => $data["title"],
                    'desc' => $data["desc"],
                    'thumb' => $data["thumb"],
                    'content' => htmlentities($data["content"]),
                    'url' => $data["url"],
                    'status' => (int)$data["status"],
                ]);
                $this->createSyslog('新增文章', $model);
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }

    public function edit($id)
    {
        $item = Article::query()->findOrFail($id);
        if (!empty($item['content'])) {
            $item['content'] = htmlspecialchars_decode($item['content']);
        }
        return $this->succeed($item);
    }

    public function update($id, Request $request)
    {
        $request->validate([
            'title' => 'required|unique:articles,title,'.$id.',id|max:120',
            'url' => 'nullable|active_url',
        ]);
        $data = $request->only(['sort', 'category_id', 'title', 'desc', 'thumb', 'content', 'url', 'status']);
        $item = Article::query()->findOrFail($id);
        try {
            DB::transaction(function () use ($item, $data) {
                $item->update([
                    'sort' => (int)$data["sort"],
                    'category_id' => (int)$data['category_id'],
                    'title' => $data["title"],
                    'desc' => $data["desc"],
                    'thumb' => $data["thumb"],
                    'content' => htmlentities($data["content"]),
                    'url' => $data["url"],
                    'status' => (int)$data["status"]
                ]);
                $this->createSyslog('更新文章', $item);
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }

    public function destroy(Request $request)
    {
        $request->validate(['ids' => 'required|array|size:'.static::QUERY_LIMIT]);
        $ids = $request->get('ids');
        try {
            DB::transaction(function () use ($ids) {
                Article::query()->whereIn('id', $ids)->limit(static::QUERY_LIMIT)->delete();
                $this->createSyslog('删除文章', $ids);
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }
}
